package com.navidove.springframework.security.impl;

import java.util.ArrayList;
import java.util.List;


import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.navidove.appspotlight.model.bo.SysUser;
import com.navidove.appspotlight.model.dao.SysUserDao;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserDao sysUserDao;
    
    /**
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {

        SysUser sysUser = sysUserDao.get(Restrictions.eq("username", userName).ignoreCase());
        if(sysUser!=null){     
            String login = sysUser.getUsername();
        	if(!login.equals(userName)){
        		sysUser=null;
        	}
        }
        if (sysUser == null) throw new UsernameNotFoundException("userName \'" + userName + "\' not found !");

        String login = sysUser.getUsername();
        String password = sysUser.getPwd();

        // Enable
        boolean enable = Boolean.TRUE.equals(sysUser.getEnable());
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        return new User(login, password, enable, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
}
